package com.berkeley.db.berkeleydb;

import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.StoreConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.io.File;

@Configuration
@PropertySource(value = {"classpath:application.yml"}, encoding = "utf-8")
public class BDBEnvironment  {

	@Value("${db.envHome}")
	private String envHome;


	@Bean
	public Environment initEnvironment() {
		EnvironmentConfig myEnvConfig = new EnvironmentConfig();
		myEnvConfig.setReadOnly(false);
		myEnvConfig.setTransactional(true);
		myEnvConfig.setAllowCreate(true);
		Environment env = new Environment(new File(envHome), myEnvConfig);
		return  env;

	}

	@Bean
	public  StoreConfig initStoreConfig(){
		StoreConfig storeConfig = new StoreConfig();
		storeConfig.setReadOnly(false);
		storeConfig.setAllowCreate(true);
		storeConfig.setTransactional(false);
		return  storeConfig;
	}

	@Bean
	public EntityStore initEntityStore(){
		return 	new EntityStore(initEnvironment(), "EntityStore", initStoreConfig());
	}
	@Bean
	public Database initDaBase (){
		DatabaseConfig databaseConfig = new DatabaseConfig();
		databaseConfig.setKeyPrefixing(true);
		databaseConfig.setAllowCreate(true); // 打开一个数据库，如果数据库不存在则创建一个
		boolean finalTransactional = true;
		//databaseConfig.setDeferredWrite(true);

		databaseConfig.setTransactional(false);
		databaseConfig.setSortedDuplicates(false);
		Database database = initEnvironment().openDatabase(null, "car", databaseConfig);//表对象
		return database;
	}



}
